package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.interceptor.LoginInterceptor;
import com.atguigu.gmall.payment.pojo.PaymentInfoEntity;
import com.atguigu.gmall.payment.pojo.UserInfo;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.payment.vo.PayAsyncVo;
import com.atguigu.gmall.payment.vo.PayVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String pay (@RequestParam("orderToken")String orderToken,Model model){

        // 根据订单编号查询订单 调用远程接口
        OrderEntity orderEntity = paymentService.queryOrderByToken(orderToken);

        // 判断订单是否为空
        if (orderEntity == null){
            throw new OrderException("订单不存在!");
        }

        // 判断订单状态是否为为未支付
        Integer status = orderEntity.getStatus();
        if (status != 0){
            throw new OrderException("该订单无法正常支付");
        }

        // 判断是否是该用户自己的订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (userId != orderEntity.getUserId()){
            //不是自己的订单
            throw new OrderException("您不能支付不属于自己的订单!");
        }
        model.addAttribute("orderEntity",orderEntity);

        return "pay";
    }

    // alipay.html?orderToken=1622166729411039234
    @GetMapping("alipay.html")
    @ResponseBody
    public String alipay(@RequestParam("orderToken")String orderToken){

        // 查询订单
        OrderEntity orderEntity = paymentService.queryOrderByToken(orderToken);
        // 判断订单是否为空
        if (orderEntity == null){
            throw new OrderException("订单不存在!");
        }

        // 判断状态是否为未支付

        if (orderEntity.getStatus() != 0){
            throw new OrderException("无法支付该订单!");
        }

        // 判断是否是自己的订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (userId != orderEntity.getUserId()){
            throw new OrderException("无法支付不属于自己的订单!");
        }

        try {
            // 调用支付宝接口打开支付界面
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderToken);
            //真实付款 设置为0.01
            payVo.setTotal_amount("0.01");
            payVo.setSubject("谷粒商城支付平台");

            // 同时设置对账信息 返回对账信息id 以便后续查询
            Long payId = paymentService.savePaymentInfo(payVo);

            //设置回调时传过来的参数 不会发生改变
            payVo.setPassback_params(payId.toString());

            return alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        throw new OrderException("打开支付界面失败，请重试!");
    }

    /**
     * 同步回调结果 不做业务处理 只做页面跳转
     * @return
     */
    @GetMapping("pay/success")
    public String paySuccess(){

        return "paysuccess";
    }

    /**
     * 异步回调接口 做业务处理
     * @return
     */
    @PostMapping("pay/ok")
    public String payOk(PayAsyncVo payAsyncVo){

        // 1验签
        Boolean flag = alipayTemplate.checkSignature(payAsyncVo);
        if (!flag){
            return "failure";
        }

        // 2校验业务参数：app_id、out_trade_no、total_amount

        String app_id = payAsyncVo.getApp_id();
        String out_trade_no = payAsyncVo.getOut_trade_no();
        String total_amount = payAsyncVo.getTotal_amount();
        //只要有一个参数不对 视为失败
        //根据对账id查询对账记录 校验参数
        String payId = payAsyncVo.getPassback_params(); //对账记录的id
        PaymentInfoEntity paymentInfoEntity = paymentService.queryPatmentInfo(payId);
        if (!StringUtils.equals(app_id,alipayTemplate.getApp_id())
                ||!StringUtils.equals(out_trade_no,paymentInfoEntity.getOutTradeNo())
                ||paymentInfoEntity.getTotalAmount().compareTo(new BigDecimal(total_amount))!= 0){
            return "failure";
        }

        // 3校验支付状态：trade_status    TRADE_SUCCESS
        if (!"TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
            return "failure";
        }

        // 4修改对账信息
        paymentInfoEntity.setTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setPaymentStatus(1);
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(payAsyncVo));
        //更新状态
        Integer inferenceRow = paymentService.updatePaymentInfo(paymentInfoEntity);
        if (inferenceRow == 1){
            // 5发送消息给MQ 解锁 减库存 加销量
            rabbitTemplate.convertAndSend("ORDER.EXCHANGE","order.pay",out_trade_no);
        }
        // 6返回success
        return "success";
    }
}
